var express = require("express")
var router = express.Router()
var User = require("../models/user")
var Category = require("../models/category")
var Content = require("../models/content")

router.get('/', function (req, res, next) {
    if (req.userInfo.isAdmin) {
        //管理员
        res.render('admin/index.html', {
            userInfo: req.userInfo
        })
    } else {
        //不是管理员
        res.redirect("http://jiangshanshan.xyz:8081")
    }
})

router.get('/user', function (req, res, next) {
    var page = Number(req.query.page || 1)  //获取问号后面的参数
    var limitNum = 10
    // 从数据库中读取所有用户数据
    User.count().then(function (count) {
        //限制page的值,不能在page总数之外
        var page_count = Math.ceil(count / limitNum)
        // console.log(page_count)
        page = Math.min(page, page_count)
        page = Math.max(page, 1)
        var skip = (page - 1) * limitNum
        User.find().limit(limitNum).skip(skip).then(function (users) {
            res.render("admin/user_index", {
                userInfo: req.userInfo,
                users: users,
                page: page,
                pages: page_count,
                limit: limitNum
            })
        })
    }
    )

})

// 分类首页
router.get('/category', function (req, res) {
    var page = Number(req.query.page || 1)  //获取问号后面的参数
    var limitNum = 10
    // 从数据库中读取所有用户数据
    User.count().then(function (count) {
        //限制page的值,不能在page总数之外
        var page_count = Math.ceil(count / limitNum)
        // console.log(page_count)
        page = Math.min(page, page_count)
        page = Math.max(page, 1)
        var skip = (page - 1) * limitNum
        Category.find().limit(limitNum).skip(skip).then(function (category) {
            res.render("admin/category_index", {
                userInfo: req.userInfo,
                categorys: category,
                page: page,
                pages: page_count,
                limit: limitNum
            })
        })
    }
    )
})

//添加分类
router.get('/category/add', function (req, res) {
    res.render('admin/category_add', {
        userInfo: req.userInfo,
    })
})

//分类保存
router.post('/category/add', function (req, res) {
    var name = req.body.name || ""
    if (name == '') {
        res.render("admin/error", {
            userInfo: req.userInfo,
            message: '名称不能为空',
        })
        return
    }
    Category.findOne({
        name: name
    }).then(function (rs) {
        if (rs) {
            //数据库中存在该分类
            res.render("admin/error", {
                userInfo: req.userInfo,
                message: "分类已存在",

            })
            return Promise.reject()
        } else {
            //保存
            return new Category({
                name: name
            }).save()
        }
    }).then(function (newcategory) {
        res.render('admin/success', {
            userInfo: req.userInfo,
            message: "保存成功",
            url: "/admin/category"
        })
    })
})

//分类修改
router.get('/category/edit', function (req, res) {
    var id = req.query._id || ""
    console.log(id)
    Category.findOne({
        _id: id
    }).then(function (category) {
        if (!category) {
            res.render('admin/error', {
                userInfo: req.userInfo,
                message: "分类信息不存在"
            })
            return Promise.reject()
        } else {
            res.render('admin/category_edit', {
                userInfo: req.userInfo,
                category: category
            })
        }
    })
})

//保存修改
router.post('/category/edit', function (req, res) {
    var name = req.body.name || ""
    var id = req.query._id || ""
    Category.findOne({
        _id: id
    }).then(function (category) {
        if (!category) {
            res.render('admin/error', {
                userInfo: req.userInfo,
                message: "分类不存在"
            })
            return Promise.reject()
        } else {
            //当用户没有做任何修改就提交的时候
            if (name == category.name) {
                res.render("admin/success", {
                    userInfo: req.userInfo,
                    message: "保存成功",
                    url: "/admin/category"
                })
                return Promise.reject()
            } else {
                //要修改的分类名称是否已经在数据库中存在
                return Category.findOne({
                    _id: { $ne: id },
                    name: name
                })
            }
        }
    }).then(function (sameCategory) {
        if (sameCategory) {
            res.render("admin/error", {
                userInfo: req.userInfo,
                message: "已有同名分类存在"
            })
            return Promise.reject()
        } else {
            return Category.update({
                _id: id
            }, {
                    name: name
                })
        }
    }).then(function () {
        res.render("admin/success", {
            userInfo: req.userInfo,
            message: "修改成功",
            url: "/admin/category"
        })
    })
})


//分类删除
router.get('/category/delete', function (req, res) {
    var id = req.query._id || ''
    Category.remove({
        _id: id
    }).then(function () {
        res.render('admin/success', {
            userInfo: req.userInfo,
            message: "删除成功",
            url: "/admin/category"
        })
    })
})


//内容首页
// router.get("/content",function(req,res){
//     res.render('admin/content_index',{
//         userInfo:req.userInfo
//     })
// })

//内容添加页面
router.get('/content/add', function (req, res) {
    Category.find().then(function (categorys) {
        res.render('admin/content_add', {
            userInfo: req.userInfo,
            categorys: categorys
        })
    })

})

//内容保存
router.post('/content/add', function (req, res) {
    if (req.body.category == '') {
        res.render("admin/error", {
            userInfo: req.userInfo,
            message: "分类不能为空"
        })
        return
    }
    if (req.body.title == '') {
        res.render("admin/error", {
            userInfo: req.userInfo,
            message: "标题不能为空"
        })
        return
    }
    //保存表单数据到数据库
    new Content({
        category: req.body.category,
        title: req.body.title,
        user:req.userInfo._id.toString(),
        description: req.body.description,
        content: req.body.content
    }).save().then(function (rs) {
        res.render("admin/success", {
            userInfo: req.userInfo,
            message: "内容保存成功"
        })
    })
})


router.get('/content', function (req, res) {
    var page = Number(req.query.page || 1)  //获取问号后面的参数
    var limitNum = 10
    // 从数据库中读取所有用户数据
    Content.count().then(function (count) {
        //限制page的值,不能在page总数之外
        var page_count = Math.ceil(count / limitNum)
        // console.log(page_count)
        page = Math.min(page, page_count)
        page = Math.max(page, 1)
        var skip = (page - 1) * limitNum
        //有一个反向查询
        Content.find().sort({ _id: -1 }).limit(limitNum).skip(skip).populate(["category","user"]).then(function (contents) {
            // console.log("contents", contents)
            // console.log(1)
            res.render("admin/content_index", {
                userInfo: req.userInfo,
                contents: contents,
                page: page,
                pages: page_count,
                limit: limitNum
            })
        })
    }
    )
})

//内容修改
router.get('/content/edit', function (req, res) {
    var id = req.query._id
    Content.findOne({
        _id: id
    }).then(function (content) {
        //promise的值不能传递,只能先保存
        var content1 = content
        Category.find().then(function(category){
          res.render("admin/content_edit", {
            content: content1,
            categorys:category
        })
        // console.log(categorys)
        })
    })
})

//内容保存
router.post("/content/edit", function (req, res) {
    var id = req.query._id
    var content = req.body.content
    var title = req.body.title
    var category = req.body.category
    var description = req.body.description
    console.log(content, title, category, description)
    Content.findOne({
        _id: id
    }).then(function (contents) {
        console.log(contents)
        if (!contents) {
            res.render("admin/error", {
                message: "没有",
                userInfo: req.userInfo
            })
            return Promise.reject()
        } else {
            if (contents.content == content && contents.title == title && contents.description === description && category == contents.category) {
                res.render("admin/success", {
                    message: "修改成功1",
                    userInfo: req.userInfo
                })
            } else {
                return Content.update({
                    _id: id
                }, {
                        title: title,
                        description: description,
                        content: content,
                        category: category
                    })
                console.log("没进到这里就没保存成功")
            }
        }
    }).then(function (contents) {
        // Content.findOne({
        // _id: id
        // }).then(function (contents) {
        console.log(contents)
        // })
        res.render("admin/success", {
            message: "修改成功2",
            userInfo: req.userInfo,
            url: "/admin/content"
        })
    })
})

router.get("/content/delete",function(req,res){
    var id = req.query._id
    Content.remove({
        _id:id
    }).then(function(){
        res.render("admin/success",{
            userInfo:req.userInfo,
            message:"删除博客成功",
            url:"/admin/content"
        })
    })
})

module.exports = router